package com.example.simpleforum.servlet;

import com.example.simpleforum.dao.UserDao;
import com.example.simpleforum.model.User;
import com.example.simpleforum.util.PasswordUtil;
import com.example.simpleforum.util.PasswordValidator;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户资料更新Servlet
 */
public class UserProfileUpdateServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取当前登录用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            // 用户未登录，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        // 获取表单参数
        String action = request.getParameter("action");
        String message = "";
        boolean success = false;
        
        UserDao userDao = new UserDao();
        
        // 根据操作类型处理不同的更新请求
        if ("updateUsername".equals(action)) {
            // 更新用户名
            String newUsername = request.getParameter("newUsername");
            
            // 验证新用户名
            if (newUsername == null || newUsername.trim().isEmpty()) {
                message = "用户名不能为空";
            } else if (newUsername.length() < 3 || newUsername.length() > 20) {
                message = "用户名长度必须在3-20个字符之间";
            } else if (userDao.isUsernameExistsExcludeSelf(newUsername, user.getId())) {
                message = "该用户名已被使用";
            } else {
                // 更新用户名
                success = userDao.updateUsername(user.getId(), newUsername);
                if (success) {
                    // 更新session中的用户信息
                    user.setUsername(newUsername);
                    session.setAttribute("user", user);
                    message = "用户名更新成功";
                } else {
                    message = "用户名更新失败，请稍后再试";
                }
            }
        } else if ("updatePassword".equals(action)) {
            // 更新密码
            String currentPassword = request.getParameter("currentPassword");
            String newPassword = request.getParameter("newPassword");
            String confirmPassword = request.getParameter("confirmPassword");
            
            // 验证密码
            if (currentPassword == null || currentPassword.trim().isEmpty() ||
                newPassword == null || newPassword.trim().isEmpty() ||
                confirmPassword == null || confirmPassword.trim().isEmpty()) {
                message = "所有密码字段都不能为空";
            } else if (!PasswordUtil.verify(currentPassword, user.getPassword())) {
                message = "当前密码不正确";
            } else if (!newPassword.equals(confirmPassword)) {
                message = "两次输入的新密码不一致";
            } else {
                // 验证密码复杂度
                String passwordInvalidReason = PasswordValidator.getInvalidReason(newPassword);
                if (passwordInvalidReason != null) {
                    message = passwordInvalidReason;
                } else {
                    // 加密新密码
                    String encryptedPassword = PasswordUtil.encrypt(newPassword);
                    // 更新密码
                    success = userDao.updatePassword(user.getId(), encryptedPassword);
                    if (success) {
                        // 更新session中的用户信息
                        user.setPassword(encryptedPassword);
                        session.setAttribute("user", user);
                        message = "密码修改成功";
                    } else {
                        message = "密码修改失败，请稍后再试";
                    }
                }
            }
        } else {
            message = "无效的操作请求";
        }
        
        // 将结果信息存入请求属性
        request.setAttribute("updateMessage", message);
        request.setAttribute("updateSuccess", success);
        
        // 转发回个人中心页面
        request.getRequestDispatcher("/UserCenterServlet").forward(request, response);
    }
}